package service

import (
	dao2 "cloudRestaurant/dao"
	"cloudRestaurant/model"
	"cloudRestaurant/param"
	"cloudRestaurant/tool"
	"encoding/json"
	"fmt"
	"log"
	"math/rand"
	"src/github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
	"time"
)

//功能实现
type MemberService struct {

}

func (ms *MemberService)SendCode(phone string)bool{
	//1.产生一个验证码
	code := fmt.Sprintf("%04v",rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(10000))
	fmt.Println(code)
	//2.调用阿里云sdk
	config := tool.GetConfig().Sms

	client, err := dysmsapi.NewClientWithAccessKey(config.RegionId, config.AppKey, config.AppSecret)
	if err!=nil{
		log.Fatal(err.Error())
		return false
	}
	request := dysmsapi.CreateSendSmsRequest()
	request.Scheme = "https"
	request.SignName = config.SignName
	request.TemplateCode = config.TemplateCode
	request.PhoneNumbers = phone
	par,err:=json.Marshal(map[string]interface{}{
		"code":code,
	})
	request.TemplateParam = string(par)
	response,err:=client.SendSms(request)
	fmt.Println(response)

	// 3.接受返回結果 判断发送状态
	if err!=nil{
		log.Fatal(err.Error())
		return false
	}
	if response.Code == "ok"{
		// 4.将code保存在数据库
		smsCode := model.SmsCode{Phone:phone,Code: code,BizId: response.BizId,CreateTime: time.Now().Unix()}
		memberDao := dao2.MemberDao{tool.DbEngine}
		result := memberDao.InsertCode(smsCode)
		return result>0
	}
	return false

}
//完成用户手机号+验证码的登录
func (ms *MemberService)SmsLogin(LoginParam param.SmsLoginParam)*model.Member{
	// 1.获取手机号和验证码
	// 2.验证手机号和验证码是否正确
	// 3.根据手机号去用户表中查询表中是否包含member数据
	// 4.如果查询不到要新建一条记录保存在member表中
	return nil
}